import re
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from django.conf import settings
from rest_framework_jwt.settings import api_settings
from celery_tasks.email.tasks import send_email
from rest_framework import  serializers

from users.models import User, Area, Address
from django_redis import get_redis_connection

class UserSerializers(serializers.ModelSerializer):
    #不需要写入数据库的要显示指明字段
    sms_code = serializers.CharField(max_length=6,write_only=True)
    password2 = serializers.CharField(max_length=20,min_length=8,write_only=True)
    allow = serializers.CharField(write_only=True)
    token = serializers.CharField(read_only=True)
    class Meta:
        model= User
        #管理操作字段
        fields = ('id','username','token','mobile','email','sms_code','password','allow','password2')
        extar_kwagrs={
            'password':{
                'max_length':20,
                'min_length':8,
                "write_only":True,
                'error_messages':{
                    'max_length':'密码过长',
                    'min_length':'密码过短'
                }

            },
            'username': {
                'max_length': 20,
                'min_length': 4,

                'error_messages': {
                    'max_length': '名字过长',
                    'min_length': '名字过短'
                }

            }
        }

    #手机号验证  正则表达式
    def validated_mobile(self,value):
        if not re.match(r'1[3-9]\d{9}$',value):
            raise serializers.ValidationError('手机格式不正确')

        return value

    #验证同意协议
    def validate_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError('协议未同意')

        return value

    #多字段联合验证密码
    def validate(self, attrs):
        if re.match(r'1[3-9]\d{9}$',attrs['username']) and attrs['username']!=attrs['mobile']:
            raise serializers.ValidationError('用户名与手机号冲突')

        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('密码不一致')

        #从redis获取真是短信验证码
        conn = get_redis_connection('verify')

        #获取数据
        real_sms_code = conn.get('sms_%s' % attrs['mobile'])
        print('真实短信验证码未', real_sms_code)
        #判断是否过期
        if not real_sms_code:
            raise serializers.ValidationError('验证码已过期')
        #转换格式
        real_sms_code = real_sms_code.decode()
        #比对验证
        # print(attrs['sms_code'],real_sms_code,'======')
        if attrs['sms_code'] != real_sms_code:
            raise serializers.ValidationError('验证码错误')

        return attrs



    def create(self, validated_data):
        del validated_data['sms_code']
        del validated_data['password2']
        del validated_data['allow']

        # user = super().create(validated_data)
        # #密码加密
        # user.set_password(validated_data['password'])
        # user.save()

        #=============使用管理器的方法,会自动加密
        user = User.objects.create_user(username=validated_data['username'],mobile=validated_data['mobile'],password=validated_data['password'])


        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user) #保存到载荷部分
        token = jwt_encode_handler(payload) #生成TOKEN

        user.token = token #序列化返回要指明在序列化中

        return user


class UserDetailSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields =('mobile','username','email','id','email_active')




class UserEmailSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields =('email',)


    def update(self, instance, validated_data):
        #instance = user
        #user = self.context['request'].user
        tjs = TJS(settings.SECRET_KEY, 300)
        token = tjs.dumps({'username': instance.username}).decode()
        try:

            send_email.delay(token, validated_data['email'])
        except BaseException as e:
            print(e)
        instance.email = validated_data['email']
        instance.save()

        return instance


class AreaSerializer(serializers.ModelSerializer):


    class Meta:
        model = Area
        fields = '__all__'


class AddressSerializer(serializers.ModelSerializer):
    province = serializers.StringRelatedField( label='省')
    city = serializers.StringRelatedField( label='市')
    district = serializers.StringRelatedField( label='区')

    province_id=serializers.IntegerField(write_only=True)
    city_id=serializers.IntegerField(write_only=True)
    district_id=serializers.IntegerField(write_only=True)
    class Meta:
        model= Address
        read_only_fields = ('province','city','district')
        exclude = ('user',)

    def create(self, validated_data):
        user = self.context['request'].user

        validated_data['user'] = user

        user = super().create(validated_data)
        return user